import qs from 'query-string';
import axios from 'axios';
import env from '../env.js';
import vueGlobal from '../vueGlobal.js';
import { getToken } from '../utils/token.js';
import { logout } from '../views/login/utils.js';

// 创建 axios 实例
const request = axios.create({
  baseURL: env.get('VUE_APP_API_BASE_URL'), // API 请求的默认前缀
  timeout: 60 * 1000, // Timeout
  withCredentials: false,
});

request.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const axiosPut = request.put;
const axiosPost = request.post;
const axiosDelete = request.delete;

request.put = function (url, data, option) {
  if (data && !(data instanceof FormData)) {
    data = qs.stringify(data);
  }
  return axiosPut(url, data, option);
};
request.putJson = function (url, data, option) {
  option = Object.assign({ headers: { 'Content-Type': 'application/json' } }, option);
  return axiosPut(url, JSON.stringify(data), option);
};
request.post = function (url, data, option) {
  if (data && !(data instanceof FormData)) {
    data = qs.stringify(data);
  }
  return axiosPost(url, data, option);
};
request.postJson = function (url, data, option) {
  option = Object.assign({ headers: { 'Content-Type': 'application/json' } }, option);
  return axiosPost(url, JSON.stringify(data), option);
};
request.deleteFormData = function (url, data, option) {
  option = Object.assign({}, option, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  });
  if (data && !(data instanceof FormData)) {
    option.data = qs.stringify(data);
  } else {
    option.data = data;
  }
  return axiosDelete(url, option);
};

// 异常拦截处理器
const errorHandler = (error) => {
  console.log('Axios Error: ', error);
  return Promise.reject(error);
};

request.onLoginOverdue = logout;
request.onLoginOffline = function (res) {
  vueGlobal.get('$message.error', 'function', (error) => {
    error(res.msg || '该账号已在其他地方登录,请重新登录!', 5);
  });
  logout();
};

request.interceptors.request.use((config) => {
  const token = getToken();
  if (token) {
    config.headers['Authorization'] = token;
  }
  return config;
}, errorHandler);

request.interceptors.response.use((response) => {
  let res = (response && response.data) || {};
  let code = String(res.code).trim();
  if (['1002', '10021'].includes(code)) {
    request.onLoginOverdue(res);
    return;
  }
  if (code === '10023') {
    request.onLoginOffline(res);
    return;
  }
  return res;
}, errorHandler);

request.install = function () {
  vueGlobal.set('$axios', request);
};

export default request;
